/*
 *  $URL$
 *  $Rev$
 *  $Date$
 *  $Id$
 *  Copyright 2009 Interactive Media Management.
 */
package com.interactivemediamanagement.converge.web.dav;

import com.bradmcevoy.http.Auth;
import com.bradmcevoy.http.CollectionResource;
import com.bradmcevoy.http.CopyableResource;
import com.bradmcevoy.http.DeletableResource;
import com.bradmcevoy.http.FileItem;
import com.bradmcevoy.http.GetableResource;
import com.bradmcevoy.http.LockInfo;
import com.bradmcevoy.http.LockResult;
import com.bradmcevoy.http.LockTimeout;
import com.bradmcevoy.http.LockableResource;
import com.bradmcevoy.http.MoveableResource;
import com.bradmcevoy.http.PostableResource;
import com.bradmcevoy.http.PropFindableResource;
import com.bradmcevoy.http.PropPatchHandler.Fields;
import com.bradmcevoy.http.PropPatchableResource;
import com.bradmcevoy.http.Range;
import com.bradmcevoy.http.Request;
import com.bradmcevoy.http.Request.Method;
import com.bradmcevoy.http.Resource;
import dk.i2m.converge.domain.NewsItem;
import dk.i2m.converge.domain.NewsItemActor;
import dk.i2m.converge.domain.UserAccount;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

/**
 *
 * @author Allan Lykke Christensen
 */
public class NewsItemResource implements PostableResource, GetableResource, PropFindableResource, DeletableResource, MoveableResource, CopyableResource, LockableResource, PropPatchableResource {

    private NewsItem article;

    private String name;

    private Date modDate;

    private Date createdDate;

    private NewsItemFolderResource parent;

    private String user;

    private String password;

    public NewsItemResource(NewsItemFolderResource parent, String name) {
        this.parent = parent;
        this.name = name;
        modDate = new Date();
        createdDate = new Date();
        if (parent != null) {
            checkAndRemove(parent, name);
            parent.children.add(this);
        }
    }

    public NewsItemResource(NewsItemFolderResource parent, String name, NewsItem article) {
        this(parent, name);
        this.article = article;
    }

    public NewsItem getArticle() {
        return article;
    }

    public void setArticle(NewsItem article) {
        this.article = article;
    }

    public void setSecure(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public NewsItemFolderResource getParent() {
        return parent;
    }

    public void setParent(NewsItemFolderResource parent) {
        this.parent = parent;
    }

    public String getHref() {
        if (parent == null) {
            return "/converge-webdav/";
        } else {
            String s = parent.getHref();
            if (!s.endsWith("/")) {
                s = s + "/";
            }
            s = s + name;
            if (this instanceof CollectionResource) {
                s = s + "/";
            }
            return s;
        }
    }

    private String getSimpleTag(String tagName, String content) {
        return "<" + tagName + ">" + content + "</" + tagName + ">";
    }

    public void sendContent(OutputStream out, Range range, Map<String, String> params) throws IOException {
        if (article != null) {
            try {
                PrintWriter printer = new PrintWriter(out, true);
                printer.print("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
                printer.print("<Root>");
                printer.print("<authors>");
                try {
                    for (NewsItemActor actor : article.getActors()) {
                        printer.print(getSimpleTag("author", actor.getUser().getFullName()));
                    }
                } catch (Throwable t) {
                    t.printStackTrace();
                }
                printer.print("</authors>");
                printer.print(getSimpleTag("title", article.getTitle()));
                printer.print(getSimpleTag("summary", article.getBrief()));
                printer.print(getSimpleTag("story", article.getStory()));
                printer.print("</Root>");
                printer.flush();
            } catch (Throwable t) {
                System.out.println("Throwup");
                t.printStackTrace();
            }
        }
    }

    public Long getContentLength() {
        return null;
    }

    public String getContentType(String accept) {
        return "text/xml";
    }

    public String checkRedirect(Request request) {
        return null;
    }

    public Long getMaxAgeSeconds() {
        return (long) 10;
    }

    public Date getCreateDate() {
        return createdDate;
    }

    public String getName() {
        return name;
    }

    public Object authenticate(String user, String password) {
        if (this.user == null) {
            return true;
        }
        return (user.equals(this.user)) && (password != null && password.equals(this.password));
    }

    public boolean authorise(Request request, Method method, Auth auth) {
        if (auth == null) {
            if (this.user == null) {
                return true;
            } else {
                return false;
            }
        } else {
            return (this.user == null || auth.user.equals(this.user));
        }
    }

    public String getRealm() {
        return "mockRealm";
    }

    public Date getModifiedDate() {
        return modDate;
    }

    protected Object clone(NewsItemFolderResource newParent) {
        NewsItemResource r = new NewsItemResource(newParent, name);
        return r;
    }

    public int compareTo(Resource o) {
        if (o instanceof NewsItemResource) {
            NewsItemResource res = (NewsItemResource) o;
            return this.getName().compareTo(res.getName());
        } else {
            return -1;
        }
    }

    public String getUniqueId() {
        return this.hashCode() + "";
    }

    private void checkAndRemove(NewsItemFolderResource parent, String name) {
        Resource r = parent.child(name);
        if (r != null) {
            parent.children.remove(r);
        }
    }

    public String processForm(Map<String, String> parameters,
            Map<String, FileItem> files) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void delete() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void moveTo(CollectionResource rDest, String name) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void copyTo(CollectionResource toCollection, String name) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public LockResult lock(LockTimeout timeout, LockInfo lockInfo) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public LockResult refreshLock(String token) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void unlock(String tokenId) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void setProperties(Fields fields) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
